package com.itc.bi.utils;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.itc.bi.config.LocalFileConfig;
import com.itc.bi.config.MinioAPI;
import com.itc.common.core.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.*;
import java.util.Base64;

/**
 * @BelongsProject: itc-airport-cloud
 * @BelongsPackage: com.itc.bi.utils
 * @Author: hecaiy
 * @CreateTime: 2024-06-21  11:10
 * @Description: TODO 图片操作工具类
 * @Version: 1.0
 */
@Slf4j
public class ImageUtil {

    /**
     * 将base64字符串转为图片文件存储
     *
     * @param base64String
     * @param fileName
     * @return
     */
    public String saveCoverPictureMinio(String base64String, String fileName, MinioAPI minioAPI) {
        String fileUrl = "";
        if (StringUtils.isBlank(base64String)) {
            return fileUrl;
        }
        // 如果不是base64字符串，直接返回 NOTE 因为如果前端截图失败，会将原封面地址传过来
        if (!base64String.startsWith("data:image")) {
            return base64String;
        }
        try {
            // 去除base64字符串前缀，从初始位置，到逗号位置
            base64String = base64String.substring(base64String.indexOf(",") + 1);
            // 解码base64字符串
            byte[] imageBytes = Base64.getDecoder().decode(base64String);
            InputStream inputStream = new ByteArrayInputStream(imageBytes);
            String filePath = "cover/"+fileName + ".png";
            minioAPI.uploadInputStream(minioAPI.getBUCKET(), filePath, inputStream, "image/png");
            fileUrl = minioAPI.getBUCKET() + "/" + filePath;
            // 封面先不保存到资源库
            // fileService.save(fileEntity);
            log.info("大屏封面保存至：{}", fileUrl);
        } catch (Exception e) {
            log.error(ExceptionUtils.getStackTrace(e));
        }
        return fileUrl;
    }

    /**
     * 将base64字符串转为图片文件存储
     *
     * @param base64String
     * @param fileName
     * @return
     */
    public String saveCoverPicture(String base64String, String fileName,LocalFileConfig localFileConfig) {
        String fileUrl = "";
        if (StringUtils.isBlank(base64String)) {
            return fileUrl;
        }
        // 如果不是base64字符串，直接返回 NOTE 因为如果前端截图失败，会将原封面地址传过来
        if (!base64String.startsWith("data:image")) {
            return base64String;
        }
        try {
            // 去除base64字符串前缀，从初始位置，到逗号位置
            base64String = base64String.substring(base64String.indexOf(",") + 1);
            // 解码base64字符串
            byte[] imageBytes = Base64.getDecoder().decode(base64String);
            InputStream inputStream = new ByteArrayInputStream(imageBytes);
            String filePath = "cover/"  + fileName + ".png";
            fileUrl = this.upload(inputStream, filePath,localFileConfig);
            // 封面先不保存到资源库
            // fileService.save(fileEntity);
            log.info("大屏封面保存至：{}", filePath);
        } catch (Exception e) {
            log.error(ExceptionUtils.getStackTrace(e));
        }
        return fileUrl;
    }


    /**
     * 将图片保存值目标目录
     * @param inputStream
     * @param fileName
     * @return
     */
    public String upload(InputStream inputStream, String fileName,LocalFileConfig localFileConfig) {
        // 上传文件保存到的路径, 从配置文件获取
        String basePath = localFileConfig.getPath();
        String destPath = basePath + "/" + fileName;
        try {
            File dest = new File(destPath);
            // 检查文件所在的目录是否存在，不存在则创建
            String parent = dest.getParent();
            File parentFile = new File(parent);
            if (!parentFile.exists()) {
                FileUtils.forceMkdir(parentFile);
            }
            FileOutputStream outputStream = new FileOutputStream(dest);
            byte[] buffer = new byte[1024];
            int length;
            while ((length = inputStream.read(buffer)) > 0) {
                outputStream.write(buffer, 0, length);
            }
            outputStream.close();
            inputStream.close();
        } catch (Exception e) {
            log.error(ExceptionUtils.getStackTrace(e));
            log.error(String.format("文件 %s 存储到 %s 失败", fileName, destPath));
            throw new ServiceException("更新图片失败");
        }
        return destPath;
    }

    /**
     * 复制封面文件
     * @param oldFileName
     * @param newFileName
     * @return
     */
    private String copyCoverPicture(String oldFileName, String newFileName,LocalFileConfig localFileConfig) {
        if (StringUtils.isBlank(oldFileName)) {
            return "";
        }
        String oldFile = "cover" + File.separator + oldFileName + ".png";
        String newFilePath = "cover" + File.separator + newFileName + ".png";
        return this.copy(oldFile, newFilePath,localFileConfig);
    }

    /**
     * 复制文件
     * @param sourcePath
     * @param targetPath
     * @return
     */
    public  String copy(String sourcePath, String targetPath,LocalFileConfig localFileConfig) {
        String basePath = localFileConfig.getPath() + File.separator;
        File sourceFile = new File(basePath + sourcePath);
        File targetFile = new File(basePath + targetPath);
        // 检查源文件是否存在
        if (!sourceFile.exists()) {
            log.error("复制源文件不存在:{}", sourcePath);
            return "";
        }
        // 检查源文件是否是文件夹
        if (sourceFile.isDirectory()) {
            log.error("源文件为文件夹:{}，无法复制", sourcePath);
            return "";
        }
        try {
            FileUtils.copyFile(sourceFile, targetFile);
        } catch (IOException e) {
            log.error(String.format("文件 %s 复制到 %s 失败", sourcePath, targetPath));
            log.error(ExceptionUtils.getStackTrace(e));
            return "";
        }
        return targetPath;
    }
}
